package org.wxl.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

public class FileUploadUtil {
    private static final String[] ALLOWED_EXTENSIONS = {
            ".jpg", ".jpeg", ".png", ".gif", ".mp4", ".avi", ".flv", ".webm", ".mp3", ".wav", ".ogg", ".pdf", ".doc", ".docx", ".xls", ".xlsx"
    };
    private static final String UPLOAD_DIR = "uploads";
    private static final String FLAG=".";
    /**
     * 通用文件上传方法
     * @param file 上传的文件对象
     * @param baseDir 基础存储目录（如："images/avatar", "videos"）
     * @return 相对存储路径（如："/uploads/images/avatar/uuid.jpg"）
     * @throws IOException 文件操作异常
     * @throws IllegalArgumentException 文件类型不合法
     */
    public static String uploadFile(MultipartFile file,String baseDir) throws IOException, IllegalArgumentException
    {
        //校验文件是否为空
        if (file.isEmpty())
        {
            throw new IllegalArgumentException("文件不能为空");
        }
        //校验文件类型
        String contentType = file.getContentType();
        if (!Arrays.asList(ALLOWED_EXTENSIONS).contains(contentType))
        {
            throw new IllegalArgumentException("不支持的文件类型: " + contentType);
        }
        //获取原始文件名并处理扩展名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(FLAG)) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf(FLAG));
        }
        String fileUuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = fileUuid + fileExtension;
        // 构建存储路径（相对于项目运行目录）
        String uploadRoot = System.getProperty("user.dir") + File.separator +UPLOAD_DIR;
        Path uploadPath = Paths.get(uploadRoot, baseDir.split("/"));
        // 创建目录（如果不存在）
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        // 保存文件
        Path targetPath = uploadPath.resolve(newFileName);
        file.transferTo(targetPath.toFile());

        // 返回相对路径
        return File.separator + "uploads" + File.separator + baseDir + File.separator + newFileName;
    }

}
